import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import Applications from '../views/Applications.vue'
import ApplicationsOverview from '../views/applications/Overview.vue'
import ApplicationsDeploy from '../views/applications/Deploy.vue'
import ApplicationsServices from '../views/applications/Services.vue'
import ApplicationsConfig from '../views/applications/Config.vue'
import Marketplace from '../views/Marketplace.vue'
import Registry from '../views/Registry.vue'
import Monitoring from '../views/Monitoring.vue'
import Settings from '../views/Settings.vue'
import Admin from '../views/Admin.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: { requiresGuest: true }
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: Dashboard,
      meta: { requiresAuth: true }
    },
    {
      path: '/applications',
      component: Applications,
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'ApplicationsOverview',
          component: ApplicationsOverview
        },
        {
          path: 'deploy',
          name: 'ApplicationsDeploy',
          component: ApplicationsDeploy
        },
        {
          path: 'services',
          name: 'ApplicationsServices',
          component: ApplicationsServices
        },
        {
          path: 'config',
          name: 'ApplicationsConfig',
          component: ApplicationsConfig
        }
      ]
    },
    {
      path: '/marketplace',
      name: 'Marketplace',
      component: Marketplace,
      meta: { requiresAuth: true }
    },
    {
      path: '/registry',
      name: 'Registry',
      component: Registry,
      meta: { requiresAuth: true }
    },
    {
      path: '/monitoring',
      name: 'Monitoring',
      component: Monitoring,
      meta: { requiresAuth: true }
    },
    {
      path: '/settings',
      name: 'Settings',
      component: Settings,
      meta: { requiresAuth: true }
    },
    {
      path: '/admin',
      name: 'Admin',
      component: Admin,
      meta: { requiresAuth: true, requiresAdmin: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()

  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.meta.requiresGuest && authStore.isAuthenticated) {
    next('/dashboard')
  } else if (to.meta.requiresAdmin && authStore.user?.role !== 'admin') {
    // 如果需要管理员权限但用户不是管理员，重定向到仪表盘
    next('/dashboard')
  } else {
    next()
  }
})

export default router
